package com.yyk.yykywd.mvvm.view_model

import android.text.Editable
import android.text.TextWatcher
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.orhanobut.logger.Logger
import com.yyk.yykywd.*
import com.yyk.yykywd.bean.BaseBean
import com.yyk.yykywd.network.BusinessApi
import com.yyk.yykywd.util.ToastUtil
import kotlinx.coroutines.launch
import java.lang.Exception

/**
 * 文件描述：
 * Created by guo on 2020-01-06.
 */
class ModifyPwdViewModel : ViewModel() {
    private var originalPwd = ""
    private var setNewPwd = ""
    private var verifyNewPwd = ""

    private var _modifyPwd = MutableLiveData<BaseBean>()
    val modifyPwd: LiveData<BaseBean>
        get() = _modifyPwd

    var originalPwdWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            originalPwd = s.trim().toString()
        }

        override fun afterTextChanged(s: Editable) {}
    }

    var setNewPwdWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            setNewPwd = s.trim().toString()
        }

        override fun afterTextChanged(s: Editable) {}
    }

    var verifyNewPwdWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            verifyNewPwd = s.trim().toString()
        }

        override fun afterTextChanged(s: Editable) {}
    }

    fun modifyPwd() {
        if (originalPwd.isEmpty()) {
            ToastUtil.showShort("请输入原密码")
            return
        }
        if (setNewPwd.isEmpty()) {
            ToastUtil.showShort("请填写新密码")
            return
        }
        if (verifyNewPwd.isEmpty()) {
            ToastUtil.showShort("请确认新密码")
            return
        }
        viewModelScope.launch {
            val newMap = getNewMap()
            putUserId(newMap)
            putPwd(newMap,originalPwd)
            putNewPwd(newMap,setNewPwd)
            putnewRePwd(newMap,verifyNewPwd)
            putSign(newMap)
            val modifyPwdAsync = BusinessApi.retrofitService.modifyPwdAsync(newMap)
            try {
                val info = modifyPwdAsync.await()
                _modifyPwd.value = info
            } catch (e: Exception) {
                Logger.e(e.toString())
            }
        }
    }
}